package com.example.demo.util;

import com.example.demo.config.SocksConnectionSocketFactory;
import com.example.demo.config.SocksSSLConnectionSocketFactory;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.*;

public class HttpClientUtil {

    public static String ting55Post(String url, String referer,String xt,String proxyHost,int porxyPort,String proxyName,String proxyPwd){
        CloseableHttpClient httpClient = null;
        try {
            Authenticator.setDefault(new Authenticator(){
                protected PasswordAuthentication getPasswordAuthentication(){
                    PasswordAuthentication p=new PasswordAuthentication(proxyName, proxyPwd.toCharArray());
                    return p;
                }
            });
            // ConnectionSocketFactory注册
            Registry<ConnectionSocketFactory> reg = RegistryBuilder.<ConnectionSocketFactory> create()
                    .register("http", new SocksConnectionSocketFactory())
                    .register("https", new SocksSSLConnectionSocketFactory(SSLContexts.createSystemDefault()))
                    .build();

            // HTTP客户端连接管理池
            PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(reg);
            httpClient = HttpClients.custom()
                    .setConnectionManager(connManager)
                    .build();
            // socks代理地址
            InetSocketAddress socketAddress = new InetSocketAddress(proxyHost, porxyPort);
            HttpClientContext context = HttpClientContext.create();
            context.setAttribute("socks.address", socketAddress);
            // 请求目标
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Referer",referer);
            httpPost.addHeader("xt",xt);
            httpPost.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3765.400 QQBrowser/10.6.4143.400");
            CloseableHttpResponse response = httpClient.execute(httpPost, context);
            String strResult = "";
            if (response.getStatusLine().getStatusCode() == 200) {
                strResult = EntityUtils.toString(response.getEntity() ,"UTF-8");
                return strResult;
            } else {
                return "Error Response: " + response.getStatusLine().toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "post failure :caused by-->" + e.getMessage();
        }finally {
            if(null != httpClient){
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /**
     * 根据url下载文件，保存到filepath中
     *
     * @param url
     * @param filepath
     * @return
     */
    public static void download(String url, String filepath,String fileName) {
        try {
            HttpClient client = HttpClients.createDefault();
            HttpGet httpget = new HttpGet(url);
            HttpResponse response = client.execute(httpget);

            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();


            File file = new File(filepath+fileName);
            file.getParentFile().mkdirs();
            FileOutputStream fileout = new FileOutputStream(file);
            /**
             * 根据实际运行效果 设置缓冲区大小
             */
            byte[] buffer = new byte[10240];
            int ch = 0;
            while ((ch = is.read(buffer)) != -1) {
                fileout.write(buffer, 0, ch);
            }
            is.close();
            fileout.flush();
            fileout.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        try {
            String proxyName = "shenwu";
            String proxyPwd = "shenwu";
            String proxyHost = "129.211.81.235";
            int porxyPort = 12355;
            Authenticator.setDefault(new Authenticator(){
                protected PasswordAuthentication getPasswordAuthentication(){
                    PasswordAuthentication p=new PasswordAuthentication(proxyName, proxyPwd.toCharArray());
                    return p;
                }
            });
            // ConnectionSocketFactory注册
            Registry<ConnectionSocketFactory> reg = RegistryBuilder.<ConnectionSocketFactory> create()
                    .register("http", new SocksConnectionSocketFactory())
                    .register("https", new SocksSSLConnectionSocketFactory(SSLContexts.createSystemDefault()))
                    .build();

            // HTTP客户端连接管理池
            PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(reg);
            CloseableHttpClient httpclient = HttpClients.custom()
                    .setConnectionManager(connManager)
                    .build();
            try {
                // socks代理地址
                InetSocketAddress socketAddress = new InetSocketAddress(proxyHost, porxyPort);
                HttpClientContext context = HttpClientContext.create();
                context.setAttribute("socks.address", socketAddress);
                // 请求目标
                HttpGet request = new HttpGet("https://www.ip.cn");
                request.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3765.400 QQBrowser/10.6.4143.400");
                CloseableHttpResponse response = httpclient.execute( request, context);
                try {
                    HttpEntity entity = response.getEntity();
                    System.out.println("----------------------------------------");
                    System.out.println("返回响应：" + response.getStatusLine());
                    System.out.println("响应内容：" + EntityUtils.toString(entity));
                    System.out.println("----------------------------------------");
                } finally {
                    response.close();
                }
            } finally {
                httpclient.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
